<template>
  <div class="survey-list">
    <a-card :title="$t('Survey Publish')" v-if="!publishStatus">
      <template #extra><a-button type="primary" @click="showModal">{{$t("Import Survey")}}</a-button></template>
      <div class="Publish">
        <a-form :model="formState" layout="vertical" @finish="onFinish" @finishFailed="onFinishFailed">
          <a-form-item :label="$t('Survey Title')" name="title" :rules="[{ required: true, message: 'Please input Survey Title!' }]">
            <a-input v-model:value="formState.title" />
          </a-form-item>
          <a-form-item :label="$t('Survey Points')" name="points" :rules="[{ required: true, message: 'Please input Survey points!' }]">
            <a-input v-model:value="formState.points" />
          </a-form-item>
          <a-form-item :label="$t('Expiration Time')" name="expireTime" :rules="[{ required: true, message: 'Please input Expiration Time!' }]">
            <a-date-picker v-model:value="formState['expireTime']" show-time format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
          </a-form-item>
          <a-form-item v-for="(item, index) in formState.questions" :key="item.id" :name="['questions', index, 'question']" :label="`${$t('Question')} ${index + 1} (${$t(questionType[item.questionType])})`" :rules="[{ required: true, message: 'Please input !' }]">
            {{$t("Question")}}：<a-input class="question-title" v-model:value="item.question" />
            <a-tooltip placement="top" :title="$t('New Options Added')" v-if="item.questionType !== 2">
              <PlusCircleTwoTone class="btn-icon" @click="addQuestionsOption(index)" />
            </a-tooltip>
            <a-tooltip placement="top" :title="$t('Delete Question')">
              <DeleteTwoTone class="btn-icon" @click="deleteQuestion(index)" />
            </a-tooltip>
            <ol style="padding-left: 42px" v-if="item.questionType !== 2">
              <li class="option-item" v-for="(option, optionIndex) in item.options" :key="option.id">
                <a-form-item class="question-option-content-title" :name="['questions', index, 'options', optionIndex, 'questionOption']" :rules="[{ required: true, message: '' }]">
                  <a-input v-model:value="option.questionOption" />
                </a-form-item>
                <a-form-item class="question-option-content" :name="['questions', index, 'options', optionIndex, 'content']" :rules="[{ required: true, message: '' }]">
                  <a-input v-model:value="option.content" />
                  <MinusCircleTwoTone class="btn-icon" type="error" @click="deleteOption(item.options, optionIndex)" />
                </a-form-item>
              </li>
            </ol>
          </a-form-item>
          <a-form-item>
            <div style="width:100%;text-align:center;">
              <a-button style="width:30%;" type="primary" html-type="submit">{{$t('Survey Publish')}}</a-button>
            </div>
          </a-form-item>
        </a-form>
        <a-card :title="$t('New Questions Added')" class="handle-list">
          <a-space direction="vertical">
            <a-button type="primary" @click="addQuestions('radio')">{{$t('Single Choice Question')}}</a-button>
            <a-button type="primary" @click="addQuestions('checkbox')">{{$t('Multiple Choice Questions')}}</a-button>
            <a-button type="primary" @click="addQuestions('text')">{{$t('Text Question')}}</a-button>
          </a-space>
        </a-card>
      </div>
    </a-card>
    <a-result status="success" :title="$t('Successfully Published')" v-if="publishStatus">
      <template #extra>
        <!-- <a-button key="console" type="primary"><router-link to="/surveyReview">{{$t("Go for review")}}</router-link></a-button> -->
        <a-button key="buy" @click="pushlishNewOne">{{$t("Publish a new Survey")}}</a-button>
      </template>
    </a-result>
    <a-modal v-model:open="open" :title="$t('Import Survey')" :footer="null">
      <div class="up-box">
        <inbox-outlined></inbox-outlined>
        <p class="ant-upload-text">Click this area to upload</p>
        <input type="file" ref="uploadInput" class="upload-input" accept=".json" @change="handleFileUpload">
      </div>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
import { reactive, toRaw, ref } from "vue";
import type { UnwrapRef } from "vue";
import {
  MinusCircleTwoTone,
  PlusCircleTwoTone,
  DeleteTwoTone,
  InboxOutlined,
} from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import { useI18n } from "vue-i18n";
import type { UploadChangeParam } from "ant-design-vue";
import { addSuevey, publishSurvey  } from "../../api/survey"
const { t } = useI18n();
const open = ref<boolean>(false);
const publishStatus = ref<boolean>(false);
const uploadInput = ref();
interface FormState {
  title: string;
  points: string;
  expireTime: any;
  questions: any[];
}
interface QuestionItem {
  surveyId: string;
  question: string;
  questionType: number;
  options: any[];
  type? : string,
}
interface questionType {
  radio: string;
  checkbox: string;
  text: string;
}

const formState: UnwrapRef<FormState> = reactive({
  title: "",
  points: "",
  expireTime: '',
  questions: [],
  id: "survey_" + new Date().getTime(),
});
const addQuestions = (type: string) => {
  let item: QuestionItem = {
    surveyId: "id_" + new Date().getTime(),
    question: "",
    questionType: type === "radio" ? 0 : (type === "text" ? 2 : 1),
    type: type,
    options: [],
  };
  formState.questions.push(item);
};

const questionType: questionType = reactive(["Single Choice Question", "Multiple Choice Questions", "Text Question"]);

const deleteQuestion = (index: number) => {
  formState.questions.splice(index, 1);
};

const handleFileUpload = (event: any) => {
  const file = event.target.files[0];
  if (file && file instanceof File) {
    const reader: any = new FileReader();
    reader.onloadend = () => {
      try {
        let jsonData = JSON.parse(reader.result);
        console.log(jsonData);
        formState.title = jsonData.title;
        formState.points = jsonData.points;
        formState.questions = jsonData.questions;
        formState.expireTime = jsonData.expireTime;
        open.value = false;
      } catch (error) {
        message.error("error");
      }
    };
    reader.readAsText(file, "UTF-8"); // 以文本形式读取文件内容
  } else {
    console.warn(t("No valid file selected!"));
  }
};
const optionMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');


const addQuestionsOption = (index: number) => {
  let existLength = formState.questions[index].options.length;
  formState.questions[index].options.push({
    id: "option_id_" + formState.questions[index].questionType + new Date().getTime(),
    questionOption: optionMap[existLength],
    content: "",
  });
};

const deleteOption = (options: any[], optionIndex: number) => {
  options.splice(optionIndex, 1);
};
const onFinish = (values: any) => {
  if (formState.questions.length === 0) {
    message.warning(t("Publiash Tips"));
    return;
  }
  
  let addParam = {
    "title":" ",
    "points": 0,
    "expireTime":" ",
    "questions":[]
}
addParam.title = formState.title;
addParam.points = formState.points;
addParam.expireTime = formState.expireTime;
let questions = []
formState.questions.forEach(item => {
  let question = {
    "question": item.question,
    "questionType": item.questionType,
    "options": []
  }
  if (item?.options?.length > 0) {
    item?.options.forEach(op => {
      let o = {"questionOption":op.questionOption,"content":op.content}
      question.options.push(o)
    })
  }
  addParam.questions.push(question)
});

  addSuevey(addParam).then(res => {
    if (res?.status == 200 ) {
      publishSurvey({id: res.data.data}).then(res1 => {
        if (res1?.status == 200 ) {
          publishStatus.value = true;
        }
      })
    }
  })

};

const onFinishFailed = (errorInfo: any) => {
  console.log("Failed:", errorInfo);
};

const showModal = () => {
  open.value = true;
};

const pushlishNewOne = () => {
  formState.title = "";
  formState.points = "";
  formState.questions = [];
  formState.expireTime = "";
  uploadInput.value.value = ""
  publishStatus.value = false;
};
</script>
<style scoped>
.Publish {
  display: flex;
  justify-content: space-around;
}
.Publish .ant-form {
  width: 70%;
}

.question-title {
  width: 50%;
}
.question-option-title {
  width: 30%;
}
.option-item {
  margin: 10px 0;
}
.btn-icon {
  cursor: pointer;
  margin-left: 10px;
}
::v-deep .ant-form-item-label {
  font-weight: bold;
}

.handle-list {
  width: 20%;
  text-align: center;
}
.handle-list button {
  width: 100%;
}
.up-box {
  position: relative;
  text-align: center;
  background: rgba(0, 0, 0, 0.02);
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  transition: border-color 0.3s;
  height: 128px;
}

.upload-input {
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  opacity: 0;
  z-index: 100;
}
.up-box .anticon {
  margin-top: 20px;
  color: #1677ff;
  font-size: 48px;
}
.option-item {
  display: flex;
  justify-content: flex-start;
}
.option-item ::v-deep .ant-form-show-help {
  width: 0;
  height: 0;
}

.option-item ::v-deep .ant-form-item-control {
  height: 30px;
}

.question-option-content-title {
  width: 10%;
}
.question-option-content {
  width: 20%;
}

.question-option-content input {
  width: 80%;
}
</style>